package top.itaso.lib.widget.tpv;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.drawable.DrawableCompat;

import top.itaso.lib.widget.R;

/**
 * @Description: IWB 系统设置 统一封装 列表 Item ，默认显示 title  + 下级页面箭头
 * @Author: itsdf07
 * @CreateDate: 2022/9/15
 */
public class TpvCommonItemView extends LinearLayout {
    private final String TAG = this.getClass().getSimpleName();
    /**
     * 控制 Item 内容的显示隐藏
     * 00000001-显示 title， =1
     * 00000010-显示 icon，  =1+2
     * 00000100-显示右侧操作（自定义图标、下级页面箭头、switch 开关）， =1+4
     * 00001000-显示 subtitle， =1+8
     * 00010000-显示 mark， =1+16
     * 00100000-显示 other， =1+32
     */
    private int layoutVisibility = 5;

    private View rootView;

    private ImageView ivIcon;
    /**
     * 需要自定义 ivIcon icon 的素材
     */
    private Drawable iconItem;
    /**
     * Item icon 尺寸，1-小尺寸，2-默认尺寸
     */
    private int iconSize;

    private TextView tvIitle;
    private String title = "";
    private int colorTitle;

    private TextView tvSubtitle;
    private String subtitle = "";
    private int colorSubTitle;

    private TextView tvMark;
    private String mark = "";
    private int colorMark;

    private TextView tvOther;
    private String other = "";
    private int colorOhter;

    private ImageView ivNext;
    /**
     * Item 右侧是下一级箭头还是开关，0-自定义 icon，1-下一级箭头，2-switch  开关
     */
    private int nextType;
    /**
     * 需要自定义 ivNext icon 的素材
     */
    private Drawable iconNext;

    private Switch switchView;

    /**
     * 用于控制 Item 右侧 箭头 图标的更换
     * 比如想要隐藏箭头、自定义图标、切换成 Switch 开关
     */
    public enum ENextType {//value 与 TpvLayoutItem_next_type 定义对应
        /**
         * 隐藏 右侧图标，也可以通过 layoutVisibility 进行隐藏
         */
        HIDE(-1),
        /**
         * 自定义 图标
         */
        CUSTOM(0),
        /**
         * 使用箭头图标
         */
        ARROW(1),
        /**
         * 使用 Switch 开关
         */
        SWITCH(2);

        public final int nativeInt;

        ENextType(int ni) {
            this.nativeInt = ni;
        }

    }

    public enum EIconSize {//value 与 TpvLayoutItem_icon_size 定义对应
        /**
         * 小图标
         */
        SMALL(1),
        /**
         * 默认图标
         */
        DEFAULT(2);

        public final int nativeInt;

        EIconSize(int ni) {
            this.nativeInt = ni;
        }

    }

    public TpvCommonItemView(Context context) {
        this(context, null);
    }

    public TpvCommonItemView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TpvCommonItemView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TpvLayoutItem);

        layoutVisibility = typedArray.getInt(R.styleable.TpvLayoutItem_layout_visibility, 5);

        nextType = typedArray.getInt(R.styleable.TpvLayoutItem_next_type, ENextType.ARROW.nativeInt);
        iconNext = typedArray.getDrawable(R.styleable.TpvLayoutItem_icon_next);

        iconSize = typedArray.getInt(R.styleable.TpvLayoutItem_icon_size, EIconSize.DEFAULT.nativeInt);
        iconItem = typedArray.getDrawable(R.styleable.TpvLayoutItem_icon_item);

        title = typedArray.getString(R.styleable.TpvLayoutItem_text_title);
        colorTitle = typedArray.getColor(R.styleable.TpvLayoutItem_color_title, getResources().getColor(R.color.color_item_text_title));

        subtitle = typedArray.getString(R.styleable.TpvLayoutItem_text_subtitle);
        colorSubTitle = typedArray.getColor(R.styleable.TpvLayoutItem_color_subtitle, getResources().getColor(R.color.color_item_text_subtitle));

        mark = typedArray.getString(R.styleable.TpvLayoutItem_text_mark);
        colorMark = typedArray.getColor(R.styleable.TpvLayoutItem_color_mark, getResources().getColor(R.color.color_item_text_subtitle));

        other = typedArray.getString(R.styleable.TpvLayoutItem_text_other);
        colorOhter = typedArray.getColor(R.styleable.TpvLayoutItem_color_other, getResources().getColor(R.color.color_text_err));

        setBackground(getResources().getDrawable(R.drawable.selector_bg_bottom_divider));
        setFocusable(true);
        setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d(TAG, "onFocusChange: >>>>>>" + v + " focus state is " + hasFocus);
            }
        });

        initView();

        setLayoutVisibility(layoutVisibility);
    }

    /**
     * 控制 Item 的可见内容
     * 00000001-显示 title， =1
     * 00000010-显示 icon，  =1+2
     * 00000100-显示右侧操作（自定义图标、下级页面箭头、switch开关）， =1+4
     * 00001000-显示 subtitle， =1+8
     * 00010000-显示 mark， =1+16
     * 00100000-显示 other， =1+32
     *
     * @param layoutVisibility
     */
    public void setLayoutVisibility(int layoutVisibility) {
        Log.d(TAG, "setLayoutVisibility: >>>>>>layoutVisibility=" + layoutVisibility);
        this.layoutVisibility = layoutVisibility;

        int visibilityStatus = layoutVisibility & (1 << 0);//1
        tvIitle.setVisibility(visibilityStatus == 0 ? GONE : VISIBLE);

        visibilityStatus = layoutVisibility & (1 << 1);//2
        ivIcon.setVisibility(visibilityStatus == 0 ? GONE : VISIBLE);

        visibilityStatus = layoutVisibility & (1 << 2);//4
        refreshNextViewVisibility(visibilityStatus != 0);

        visibilityStatus = layoutVisibility & (1 << 3);//8
        tvSubtitle.setVisibility(visibilityStatus == 0 ? GONE : VISIBLE);

        visibilityStatus = layoutVisibility & (1 << 4);//16
        tvMark.setVisibility(visibilityStatus == 0 ? GONE : VISIBLE);

        visibilityStatus = layoutVisibility & (1 << 5);//16
        tvOther.setVisibility(visibilityStatus == 0 ? GONE : VISIBLE);

        //确保 Adapter 中 onCreateViewHolder 直接 new 出该 View 时，是可以横向填充的
        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        if (layoutParams == null) {
            layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        } else {
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        }
        setLayoutParams(layoutParams);

        //重置 tvIitle 控件在约束布局中的右侧对齐目标，确保不会与 tvMark、switchView 或者 ivNext 控件出现重叠
//        ConstraintLayout.LayoutParams titleParams = (ConstraintLayout.LayoutParams) tvIitle.getLayoutParams();
//        if (tvMark.getVisibility() == View.VISIBLE) {
//            ConstraintLayout.LayoutParams markParams = (ConstraintLayout.LayoutParams) tvMark.getLayoutParams();
//            markParams.rightToLeft = switchView.getVisibility() == View.VISIBLE ? switchView.getId() : ivNext.getId();
//            tvMark.setLayoutParams(markParams);
//
//            titleParams.rightToLeft = tvMark.getId();
//        } else {
//            titleParams.rightToLeft = switchView.getVisibility() == View.VISIBLE ? switchView.getId() : ivNext.getId();
//        }
//        titleParams.leftToRight = ivIcon.getId();
//
//        tvIitle.setLayoutParams(titleParams);
    }

    /**
     * 控制 Item 右侧使用 icon 的类型，该 View 不显示时设置无效
     *
     * @param nextType -1表示隐藏，0-自定义icon，1-下一级箭头，2-switch开关
     * @see ENextType
     */
    public void setNextType(ENextType nextType) {
        this.nextType = nextType.nativeInt;
    }

    /**
     * 设置 Item 图标尺寸大小，如权限图标
     *
     * @param sizeType
     * @see EIconSize
     */
    public void setIconSize(EIconSize sizeType) {
        setIconSize(sizeType.nativeInt);
    }

    /**
     * 二次缩进
     */
    public void setTitleRetractLeftSecond() {
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) tvIitle.getLayoutParams();
        if (params == null) {
            params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
        }
        params.setMargins(getResources().getDimensionPixelSize(R.dimen.dimen_tpv_item_retract_left_second), 0, params.getMarginEnd(), 0);
        tvIitle.setLayoutParams(params);
    }


    /**
     * 设置 Icon 图片，ivIcon 可见时有效
     *
     * @param res
     */
    public void setIconImageDrawable(Drawable res) {
        if (ivIcon.getVisibility() == View.GONE) {
            return;
        }
        ivIcon.setImageDrawable(res == null ? getResources().getDrawable(R.mipmap.ic_setup_pressed) : res);
    }

    /**
     * 自定义并替换原展示 下一级页面的 箭头图标，且只有在 nextType = NextType.CUSTOM 时有效
     *
     * @param res
     */
    public void setCustomImageDrawable(Drawable res) {
        if (nextType != ENextType.CUSTOM.nativeInt) {
            return;
        }
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) ivNext.getLayoutParams();
        if (params == null) {
            params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
        } else {
            params.width = getResources().getDimensionPixelSize(R.dimen.dimen_30);
            params.height = params.width;
        }
        ivNext.setLayoutParams(params);
//        ivNext.setScaleType(ImageView.ScaleType.FIT_XY);

        ivNext.setImageDrawable(res == null ? getResources().getDrawable(R.drawable.selector_ic_next) : res);
    }

    public void setTitleContent(String content) {
        title = content;
        tvIitle.setText(content);
    }

    public String getTitleContent() {
        return tvIitle == null ? "" : tvIitle.getText().toString();
    }

    public void setSubTitleContent(String content) {
        if (tvSubtitle.getVisibility() == View.GONE) {
            return;
        }
        subtitle = content;
        tvSubtitle.setText(content);
    }

    public void setMarkContent(String content) {
        if (tvMark.getVisibility() == View.GONE) {
            return;
        }
        mark = content;
        tvMark.setText(content);
    }

    public void setOtherContent(String content) {
        if (tvOther.getVisibility() == View.GONE) {
            return;
        }
        other = content;
        tvOther.setText(content);
    }

    public void setSwitchStatus(boolean isChecked) {
        switchView.setChecked(isChecked);
    }

    public boolean getSwitchStatus() {
        return switchView.isChecked();
    }

    public Drawable tintDrawable(Drawable drawable) {
        return tintDrawable(drawable, Color.parseColor("#575757"));//R.color.color_icon_tint_drawable
    }

    @Deprecated
    public void setItemOnClickListener(OnClickListener listener) {
        setOnClickListener(view -> {
            if (listener != null) {
                listener.onClick(view);
            }
        });
    }

    /**
     * 只有在 nextType = NextType.CUSTOM 时有效
     *
     * @param listener
     */
    public void setCustomOnClickListener(OnClickListener listener) {
        if (nextType != ENextType.CUSTOM.nativeInt) {
            return;
        }
        ivNext.setFocusable(true);
        ivNext.setEnabled(true);
        setNextFocusRightId(R.id.iv_item_next);
        ivNext.setOnClickListener(listener);
    }

    public void setItemOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener) {
        switchView.setOnCheckedChangeListener((compoundButton, isChecked) -> {
            Log.d(TAG, "onCheckedChanged: >>>>>>compoundButton=" + compoundButton.isPressed() + ",b=" + compoundButton);
            if (listener != null) {
                listener.onCheckedChanged(compoundButton, isChecked);
            }
        });
    }


    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
//        rootView = inflate(getContext(), R.layout.layout_common_item_2_result_list, this);
        rootView = LayoutInflater.from(getContext()).inflate(R.layout.layout_tpvsettings_common_item, this, false);
//        rootView.setId(getId());
        addView(rootView);
        rootView.setOnFocusChangeListener((v, hasFocus) ->
                Log.d(TAG, "onFocusChange: >>>>>>rootView 的 focus 事件，hasFocus=" + hasFocus)
        );

        ivIcon = findViewById(R.id.iv_item_icon);
        setIconSize(iconSize);
        setIconImageDrawable(iconItem);

        tvIitle = findViewById(R.id.tv_item_title);
        tvIitle.setText(title);
        tvIitle.setTextColor(colorTitle);

        tvSubtitle = findViewById(R.id.tv_item_subtitle);
        tvSubtitle.setText(subtitle);
        tvSubtitle.setTextColor(colorSubTitle);

        tvMark = findViewById(R.id.tv_item_status_mark);
        tvMark.setText(mark);
        tvMark.setTextColor(colorMark);

        tvOther = findViewById(R.id.tv_item_other);
        tvOther.setText(other);
        tvOther.setTextColor(colorOhter);

        ivNext = findViewById(R.id.iv_item_next);
        setCustomImageDrawable(iconNext);

        switchView = findViewById(R.id.switch_item_turn_off);

        ivNext.setFocusable(false);//屏蔽遥控器焦点的聚焦，目的是这边将所有点击事件统一放在 Item 上管理
        switchView.setFocusable(false);//屏蔽遥控器焦点的聚焦，目的是这边将所有点击事件统一放在 Item 上管理

        switchView.setOnTouchListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                performClick();
            }
            return true;
        });
//
//        ivNext.setOnTouchListener((view, motionEvent) -> {
//            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
//                performClick();
//            }
//            return true;
//        });
    }

    /**
     * 设置 Item 图标尺寸大小，如权限图标
     *
     * @param size
     * @see EIconSize
     */
    private void setIconSize(int size) {
        int width;
        if (size == EIconSize.SMALL.nativeInt) {
            width = getResources().getDimensionPixelSize(R.dimen.dimen_item_icon_size_small);
        } else {
            width = getResources().getDimensionPixelSize(R.dimen.dimen_item_icon_size_default);
        }
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) ivIcon.getLayoutParams();
        if (params == null) {
            params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
        }
        params.width = width;
        params.height = width;
        ivIcon.setLayoutParams(params);
    }

    private void refreshNextViewVisibility(boolean isVisible) {
        if (!isVisible) {
            ivNext.setVisibility(GONE);
            switchView.setVisibility(GONE);
            return;
        }
        ivNext.setVisibility((nextType == ENextType.CUSTOM.nativeInt
                || nextType == ENextType.ARROW.nativeInt)
                ? View.VISIBLE : View.GONE);
        switchView.setVisibility(nextType == ENextType.SWITCH.nativeInt ? View.VISIBLE : View.GONE);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private Drawable tintDrawable(Drawable drawable, int colors) {
        Drawable wrappedDrawable = DrawableCompat.wrap(drawable).mutate();
        DrawableCompat.setTint(wrappedDrawable, colors);
        return wrappedDrawable;
    }
}
